<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use zgldh\QiniuStorage\QiniuStorage;
use App\Hair;
use Input;
use App\HairColor;

class HairController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //查询出hair style
        $datas = Hair::select('hairid','hairname','hairtype','hairsex','hairthumb','hairwidth','hairheight','leftx','lefty','rightx','righty','sort','status')->paginate('30');
        return view('admin.hair.index',compact('datas'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //显示添加页面
        return view('admin.hair.add');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {//?imageMogr2/thumbnail/110x110
        //生成缩略图
        $this -> validate($request,[
            'hairname'    => 'required|max:50',
            'thumbwidth'  => 'required|numeric',
            'thumbheight' => 'required|numeric',
            'leftx'       => 'required|numeric',
            'rightx'      => 'required|numeric',
            'lefty'       => 'required|numeric',
            'righty'      => 'required|numeric',
            'sort'        => 'required|numeric',
        ],[
            'hairname.required'     =>  '名称需要填写',
            'hairname.max'          =>  '名称过长',
            'thumbwidth.numeric'    =>  '缩略像素宽请输入数字',
            'thumbwidth.required'   =>  '缩略像素宽没有输入',
            'thumbheight.numeric'   =>  '缩略像素高请输入数字',
            'thumbheight.required'  =>  '缩略像素高没有输入',
            'leftx.required'        =>  'leftx需要填写',
            'rightx.required'       =>  'rightx需要填写',
            'lefty.required'        =>  'leftx需要填写',
            'righty.required'       =>  'rightx需要填写',
        ]);
        //获取数据
        $hairname     =  trim(Input::get('hairname'));
        $hairthumb    =  trim(Input::get('hairthumb'));
        $leftx        =  trim(Input::get('leftx'));
        $rightx       =  trim(Input::get('rightx'));
        $lefty        =  trim(Input::get('lefty'));
        $righty       =  trim(Input::get('righty'));
        $sort         =  trim(Input::get('sort'));
        $hairtype     =       Input::get('hairtype');
        $hairsex      =       Input::get('hairsex');
        $status       =       Input::get('status');
        $thumbwidth   =  trim(Input::get('thumbwidth'));
        $thumbheight  =  trim(Input::get('thumbheight'));
        //首先判断文件是否正常
        if($request ->hasFile('file')){
            $file = Input::file('file');
            //这里需要先获取到原图片的高度和宽度
            //将数据组装成数据进行数据判断,还有文件
            $extension = $file->getClientOriginalExtension();
            $extension = strtolower($extension);
            if(!in_array( $extension,['png','jpg']))
            return back() -> with(['info'=>'需要png类型或者jpg类型']);
            //首先获取它的扩展名
            $clientName = $file->getClientOriginalName();
            //将文件进行移动
            $newName = md5(date('Y-m-d H:i:s') . $clientName) . "." . $extension;
            //先判断是否有cimg这个目录
            $filename = 'cimg';
            if(file_exists($filename)){
                //判断是否是一个目录
                if(!is_dir($filename)){
                    mkdir('cimg','07777');
                }
            }else{
                //创建目录
                mkdir('cimg','07777');
            }
            $path   = $file->move('cimg', $newName);
            $bigpicname = 'cimg//'.$newName;
            $size = getimagesize($path);
            //图片的宽
            $hairwidth = $size['0'];
            //图片的高
            $hairheight = $size['1'];
            //创建文件的缩略图
            //cimg下面是原型图
            //tim下面是缩略图
            $disk   = QiniuStorage::disk('qiniu');
            $bool = $disk->put('cimg/'.$newName,file_get_contents($bigpicname));
            if($bool){
                //则说明大图已经进入到了七牛；然后获取七牛地址;
                $qnpath = $disk -> downloadUrl('cimg/'.$newName);
                //然后生成缩略图；并且放到七牛；

                $smallpath = $qnpath.'?imageMogr2/thumbnail/'.$thumbwidth.'x'.$thumbheight;
                //自定义路径
                $hairthumb = 'hair/'.md5(date('Y-m-d H:i:s') . $clientName.'const') . "." . $extension;
                $sbool = $disk -> put($hairthumb,file_get_contents($smallpath));
                if($sbool){
                    $res = Hair::create(['hairname'=>$hairname,'hairtype'=>$hairtype,'hairsex'=>$hairsex,'hairthumb'=>$hairthumb,'hairwidth'=>$hairwidth,'hairheight'=>$hairheight,'leftx'=>$leftx,'rightx'=>$rightx,'lefty'=>$lefty,'righty'=>$righty,'sort'=>$sort,'status'=>$status]);
                   if($res){
                       $delete =  $disk -> delete('cimg/'.$newName);
                       if($delete)
                       return back() -> with(['info'=>'添加成功']);
                       return back() -> with(['info'=>'添加成成功,请手动删除已经上传的大图地址:cimg/'.$newName]);
                   }
                }else{
                    return back() -> with(['info'=>'not into qiniu']);
                }
                }else{
                        //不论成功与否，都删除掉上传的大图
                        $delete = $disk -> delete('cimg/'.$newName);
                        if($delete)
                        return back() -> with(['info'=>'上传失败,请重新上传']);
                        return back() -> with(['info'=>'上传失败,请手动删除已经上传的大图地址cim/'.$newName]);
                }
                //将数据插入数据库

        }
        return back() -> with(['info'=>'no pic']);

    }
    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //显示详情
        $datas = Hair::where('hairid',$id)->select('*')->first();
        return view('admin.hair.show',compact('datas'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $datas = Hair::where('hairid',$id)->first();
        return view('admin.hair.edit',compact('datas'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //进行表单验证;
        $hairname    = trim(Input::get('hairname'));
        $hairtype    = Input::get('hairtype');
        $hairsex     = Input::get('hairsex');
        $hairwidth   = Input::get('hairwidth');
        $hairheight  = Input::get('hairheight');
        $leftx       = Input::get('leftx');
        $lefty       = Input::get('lefty');
        $rightx      = Input::get('rightx');
        $righty      = Input::get('righty');
        $sort        = Input::get('sort');
        $status      = Input::get('status');
        $thumbwidth  = Input::get('thumbwidth');
        $thumbheight = Input::get('thumbheight');
        //以隐藏域传来的hairthumb;
        $hairthumb  = trim(Input::get('hairthumb'));
        if(!($request ->hasFile('file'))){
            //执行更新
            $res = Hair::where('hairid',$id)->update(['hairname'=>$hairname,'hairtype'=>$hairtype,'hairsex'=>$hairsex,'hairwidth'=>$hairwidth,'hairheight'=>$hairheight,'leftx'=>$leftx,'lefty'=>$lefty,'rightx'=>$rightx,'righty'=>$righty,'sort'=>$sort,'status'=>$status]);
            if($res === false)
            return back() -> with(['info'=>'更新不成功']);
            return Redirect('hair')->with(['info'=>'更新成功']);

        }else{
            //说明有缩略图传来;
            $file = Input::file('file');
            //这里需要先获取到原图片的高度和宽度
            //将数据组装成数据进行数据判断,还有文件
            $extension = $file->getClientOriginalExtension();
            $extension = strtolower($extension);
            if (!in_array($extension, ['png','jpg']))
            return back()->with(['info' => '需要png类型或者jpg类型']);
            //首先获取它的扩展名
            $clientName = $file->getClientOriginalName();
            //先判断是否有cimg这个目录
            $filename = 'cimg';
            if(file_exists($filename)){
                //判断是否是一个目录
                if(!is_dir($filename)){
                    mkdir('cimg','07777');
                }
            }else{
                //创建目录
                mkdir('cimg','07777');
            }
                 //将文件进行移动
            $newName = md5(date('Y-m-d H:i:s') . $clientName) . "." . $extension;
            $path = $file->move('cimg', $newName);
            $bigpic = 'cimg//'.$newName;
            $size = getimagesize($path);
            //图片的宽
            $hairwidth = $size['0'];
            //图片的高
            $hairheight = $size['1'];
            //创建文件的缩略图
            //cimg下面是原型图
            //tim下面是缩略图
            $disk = QiniuStorage::disk('qiniu');
            //先删七牛上的图片,然后再存入图片
            //将文件进行移动
            $newName = md5(date('Y-m-d H:i:s') . $clientName) . "." . $extension;
                //首先存入大图
                $bool = $disk->put('cimg/'.$newName, file_get_contents($bigpic));
                if ($bool) {
                    //存入大图成功;则生成缩略图；并且删除大图
                    $qnpath = $disk -> downloadUrl('cimg/'.$newName);
                    //然后生成缩略图；并且放到七牛；
                    $smallpath = $qnpath.'?imageMogr2/thumbnail/'.$thumbwidth.'x'.$thumbheight;
                    //自定义路径
                    $newhairthumb = 'hair/'.md5(date('Y-m-d H:i:s') . $clientName.'const') . "." . $extension;
                    $sbool = $disk -> put($newhairthumb,file_get_contents($smallpath));
                    if($sbool){
                        $res = Hair::where('hairid',$id)->update(['hairname'=>$hairname,'hairtype'=>$hairtype,'hairsex'=>$hairsex,'hairthumb'=>$newhairthumb,'hairwidth'=>$hairwidth,'hairheight'=>$hairheight,'leftx'=>$leftx,'rightx'=>$rightx,'lefty'=>$lefty,'righty'=>$righty,'sort'=>$sort,'status'=>$status]);
                        if($res){
                            $delete =  $disk -> delete('cimg/'.$newName);
                            if($delete){
                                $deletes = $disk -> delete($hairthumb);
                                if($deletes)
                                return back() -> with(['info'=>'更新成功']);
                                return back() -> with(['info'=>'更新成功,但原图没有删除地址是'.$hairthumb]);
                            }else{
                                $deletes = $disk -> delete($hairthumb);
                                if($deletes)
                                return back() -> with(['info'=>'更新成功,但是生成缩略图的大图删除失败地址是cim/'.$newName]);
                                return back() -> with(['info'=>'更新成功,但是原图片和生成缩略的的大图删除失败:地址分别是:'.$hairthumb.'cimg/'.$newName]);
                            }
                        }else{
                            return back() -> with(['info'=>'数据库更新失败,图片已经存到七牛云.地址是:'.$hairthumb]);
                        }
                        }else{
                        return back() -> with(['info'=>'存入缩略图失败']);
                        }
                    } else {
                        return back()->with(['info' => '存入七牛时出错']);
                    }
                }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $datas = Hair::where('hairid',$id)->first();
        //根据hair_style的id获取hair_color中是否有数据，如果有，就不删除了
        $have = HairColor::where('hairid',$id) -> first();
        if(empty($have)){
            //则删除七牛中存储的数据
                $hairthumb = $datas['hairthumb'];
                $disk   = QiniuStorage::disk('qiniu');
                $res = Hair::where('hairid',$id)->delete();
                if($res){
                    $bool   = $disk -> delete($hairthumb);
                    if($bool){
                        return Response() -> json(['status'=>'success','msg'=>'删除成功']);
                    }else{
                        return Response() -> json(['status'=>'error','msg'=>'删除七牛图片失败']);
                    }
                }else{
                    return Response() -> json(['status' => 'error','msg'=>'删除失败']);
                }

            }else{
            return Response() -> json(['status'=>'havechild','msg'=>'下面有数据,有数据不能删除']);
        }
    }
    public function hair_status()
    {
        $hairid = Input::get('hairid');
        $status = Input::get('cstatus');
        //修改状态:
        $res = Hair::where('hairid',$hairid) -> update(['status'=>$status]);
        if($res)
        return Response() -> json(['status'=>'success','msg'=>'更改成功']);
        return Response() -> json(['status'=>'error','msg'=>'修改失败']);

    }
}
